<!DOCTYPE html>
<html>

<head>
  <title>
    <%= title %>
  </title>
  <link rel='stylesheet' href='/stylesheets/style.css' />
</head>

<body>
  <h1>个人通讯录</h1>
  <div>
    <div>
        id:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="text" id="userId">
    </div>
    <div>
      姓名: <input type="text" id="username">
    </div>
    <div>
      住址: <input type="text" id="address">
    </div>
    <div>电话: <input type="text" id="tel"></div>
    <div><button id="register">添加</button></div>
  </div>
  <hr>
  <div>
    <button id="update">更新</button>
    <button id="delete">删除</button>
  </div>

  <table border="1">
    <thead>
      <tr>
        <td>id</td>
        <td>用户名</td>
        <td>住址</td>
        <td>电话</td>
      </tr>
    </thead>
    <tbody>

    </tbody>
  </table>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    let register = document.querySelector("#register")
    let userId = document.querySelector("#userId")
    let address = document.querySelector("#address")
    let tel = document.querySelector("#tel")
    let username = document.querySelector("#username")
    let update = document.querySelector("#update")
    let del = document.querySelector("#delete")
    let tbody = document.querySelector("tbody")

     // 获取
    function getData() {
        axios.get("api/user?page=1&limit=10").then((res) => {
    //   console.log(res.data, 123456);
      tbody.innerHTML = res.data.map(item => `
        <tr>
          <td>${item._id}</td>  
          <td>${item.username}</td>  
          <td>${item.address}</td>  
          <td>${item.tel}</td>  
        </tr>
      `).join("")
    }).catch(err => {
      console.log(err);
    })
    }
    getData()


    // 添加
    register.onclick = () => {
      axios.post('/api/user', {
        username: username.value,
        address: address.value,
        tel: tel.value
      }).then(res => {
        // console.log(res.data);
        getData()
      }).catch(err => {
        console.log(err);
      })
    }

    //更新
    update.onclick = () => {
        console.log(userId.value);
      axios.put(`/api/user/${userId.value}`, {
        username: username.value,
        address: address.value,
        tel: tel.value
      }).then(res => {
        // console.log(res.data);
        getData()
      }).catch(err => {
        console.log(err);
      })
    }

    // 删除
    del.onclick = () => {
      axios.delete(`/api/user/${userId.value}`).then(res => {
        // console.log(res.data);
        getData()
      }).catch(err => {
        console.log(err);
      })
    }

   
  </script>
</body>

</html>